package cn.wolfcode.p2p.base.service.impl;

import cn.wolfcode.p2p.base.exception.CustomerException;
import cn.wolfcode.p2p.base.mapper.UserInfoMapper;
import cn.wolfcode.p2p.base.service.IUserInfoService;

import cn.wolfcode.p2p.base.domain.UserInfo;
import java.util.List;
import cn.wolfcode.base.QueryObject;
import cn.wolfcode.p2p.base.util.BitStateUtil;
import cn.wolfcode.p2p.base.util.LoginInfoContext;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserInfoServiceImpl implements IUserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
	
	@Transactional(readOnly=true)
	public PageInfo<UserInfo> query(QueryObject qo) {
		PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
		List<UserInfo> list = userInfoMapper.selectList(qo);
		return new PageInfo<UserInfo>(list);
	}

	@Override
	public UserInfo get(Long id) {
		return userInfoMapper.selectById(id);
	}

	@Override
	public void saveUserInfo(UserInfo vo) {
		// 完善个人信息, 为了数据安全, 先获取该用户的信息, 再将需要的数据插入, 不是整个对象插入
		UserInfo userInfo = this.get(LoginInfoContext.getCurrentLoginInfo().getId());

		userInfo.setMarriage(vo.getMarriage())
				.setKidCount(vo.getKidCount())
				.setEducationBackground(vo.getEducationBackground())
				.setHouseCondition(vo.getHouseCondition())
				.setIncomeGrade(vo.getIncomeGrade());

		// 更新状态码
        userInfo.addNewState(BitStateUtil.OP_BASIC_INFO);
		// 更新
		this.update(userInfo);
	}

	@Override
	public void update(UserInfo userInfo) {
		int rows = userInfoMapper.updateById(userInfo);

		if (rows == 0){
			throw new CustomerException("乐观锁失败, Account.id : " + userInfo.getId());
		}
	}
}
